﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.DataEncryption;
using HiCore.WebApi.Example.DbContexts.DbEntity;
using HiCore.WebApi.Example.DbContexts.Encryption;
using HiCore.WebApi.Example.DbContexts.Interceptors;

namespace HiCore.WebApi.Example.DbContexts
{
    public class MyDbContext : DbContext
    {
        private readonly IServiceProvider _serviceProvider;
        public MyDbContext(DbContextOptions<MyDbContext> options, IServiceProvider serviceProvider) : base(options)
        {
            _serviceProvider = serviceProvider;
        }

        public DbSet<TestTable> Test { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.AddInterceptors(new DomainEventInterceptor(_serviceProvider));

            optionsBuilder.AddInterceptors(new AuditInterceptor(_serviceProvider));


            //optionsBuilder.UseMySql("server=10.10.10.19;port=4000;uid=root;pwd=;Database=api2;Character Set=utf8;", new MySqlServerVersion(new Version(8, 0, 27)));
            //optionsBuilder.UseMySql(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            string MD5_AESKey = MD5Utility.CreateMD5Lower32(AESUtility.AesKey);
            string MD5_AesVI = MD5Utility.CreateMD5Lower16(AESUtility.AesVI);

            modelBuilder.UseEncryption(new AESProvider(Encoding.Default.GetBytes(MD5_AESKey), Encoding.Default.GetBytes(MD5_AesVI)));

            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }
    }
}
